package com.zy.springboot_nanhua4.controllers;

import com.zy.springboot_nanhua4.model.Student;
import com.zy.springboot_nanhua4.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping(value="/find/{id}") // localhost:8080/student/find/1
    public ResponseEntity<ResponseResult> findById(@PathVariable Integer id){
        Student s=studentService.find(id);
        if(s==null){
            return ResponseEntity.ok(ResponseResult.error("查无此id号的学生"));
        }
        return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }
    @PostMapping(value="/add")
    public ResponseEntity<ResponseResult> add (Student s){
        System.out.println(s);
        s =  studentService.add(s);
        boolean b = true;
        //boolean b = studentService.add (s);
        if (!b){
            return ResponseEntity.ok ( ResponseResult.error ("添加失败") );
        }
        return ResponseEntity.ok ( ResponseResult.ok ().setData (s) );
    }
    @GetMapping(value="/findByName")
    public ResponseEntity<ResponseResult<List<Student>>> findByName(@RequestParam(value="name",required = false) String name){
        List<Student> list=studentService.findByName(name);
        ResponseResult rr=ResponseResult.ok().setData(list);
        return ResponseEntity.ok(rr);
    }
    @DeleteMapping(value="/delete/{id}")
    public ResponseEntity<ResponseResult> deleteById(@PathVariable Integer id){
        studentService.delete(id);

        return ResponseEntity.ok(ResponseResult.ok().setData("删除编号为："+id+"的学生成功"));
    }

    @PutMapping(value = "/update")
    public ResponseEntity<ResponseResult> update( Student s){
        System.out.println(s);
        s=studentService.update(s);
        boolean b=true;
        if(!b){
            return ResponseEntity.ok(ResponseResult.error("修改失败"));

        }
        return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }
}